# coding:utf-8
import os.path
import sys
import time

from utils.pan123 import upload_file_pan123, off_download_file_pan123

sys.path.append(os.getcwd())
import configparser
import os
import sys
from threading import Thread
from urllib.parse import urlparse
import requests
import uvicorn
from fastapi import FastAPI
from pydantic import BaseModel
from loguru import logger

from utils.dbtools import update_by_id, create_task, query_pan123_file_name
from utils.u_qiniu import upload2qiniu, is_file_processed
from utils.common import send_wx_template, exec_cmd, set_scale, check_img, send_warn_msg

app = FastAPI()

if getattr(sys, 'frozen', False):
    BASE_DIR = os.path.dirname(sys.executable)
elif __file__:
    BASE_DIR = os.path.dirname(__file__)

logger.debug(f'BASE_DIR:{BASE_DIR}')
# 创建 ConfigParser 实例
config = configparser.ConfigParser()
config.read(os.path.join(BASE_DIR,'config.ini'),encoding='utf-8')  # 替换为您的配置文件路径

#app
host = config.get('app', 'host')
port = config.get('app', 'port')
log_level = config.get('app', 'log_level')
TOPAZ_DIR = config.get('app', 'TOPAZ_DIR')
registry_path = config.get('app', 'registry_path')
registry_value_name = config.get('app', 'registry_value_name')
#qiniu
url_preffix = config.get('qiniu', 'url_preffix')


app = FastAPI()

# 创建一个 Pydantic 模型来定义 JSON 参数
class Item(BaseModel):
    fileName: str

DOWNLOAD_TMP = 'download'

def download_file(file_url):
    os.makedirs(DOWNLOAD_TMP, exist_ok=True)
    file_url = file_url.replace('https','http')
    logger.debug(f'file_url:{file_url}')
    response = requests.get(file_url)

    # 检查响应状态码是否为 200 (表示成功)
    if response.status_code == 200:
        logger.info(file_url)
        parsed_url = urlparse(file_url)
        # 从解析后的 URL 中获取文件名部分
        file_name = str(parsed_url.path.split("/")[-1])
        logger.info(file_name)

        # 以二进制写模式打开文件，并写入响应内容
        with open(os.path.join(DOWNLOAD_TMP, file_name), 'wb') as file:
            file.write(response.content)
        logger.debug(f"文件 '{file_name}' 下载完成")
        return True
    else:
        logger.debug("下载失败，状态码:", response.status_code)
        return False


# 创建路由，接受 JSON 参数
@app.post("/processPic/")
async def processPic(item: Item):
    fileName = item.fileName
    logger.info(fileName)
    if len(fileName.split('--')) > 4:
        #判断图片是否被处理过，
        isProcessed = is_file_processed(fileName)

        before_link = f'{url_preffix}{fileName}'
        off_download_file_pan123(before_link)
        logger.debug(f'before_link:{before_link}')
        scale = fileName.split('--')[-1].split('.')[0]

        pan123_file_name = query_pan123_file_name(fileName)

        if (isProcessed != None) and (pan123_file_name!=None):
            # 已处理过的，通过task_id查找pan123的文件名
            send_wx_template(fileName,pan123_file_name)
            return 'ok'
        else:
            # 下载文件
            download_status = download_file(before_link)
            if download_status:
                create_task(fileName, 0, '文件下载成功')
                input_file = os.path.join(BASE_DIR, DOWNLOAD_TMP,fileName)
                Thread(target=topaz_cmd, args=(input_file,scale)).start()
                return 'ok'
            else:
                create_task(fileName, 1, '文件下载失败')
                return 'fail'
    else:
        # 判断图片是否被处理过，
        logger.info(fileName)
        isProcessed = is_file_processed(fileName)
        logger.info(f'isProcessed:{isProcessed}')

        before_link = f'{url_preffix}{fileName}'
        off_download_file_pan123(before_link)
        logger.debug(f'before_link:{before_link}')
        scale = 4

        pan123_file_name = query_pan123_file_name(fileName)
        logger.info(f'pan123_file_name:{pan123_file_name}')

        if (isProcessed != None) and (pan123_file_name != None):
            # 已处理过的，通过task_id查找pan123的文件名
            send_wx_template(fileName, pan123_file_name)
            return 'ok'
        else:
            if len(fileName.split('----'))>1:
                #被封禁用户
                return 'fail'
            # 下载文件
            download_status = download_file(before_link)
            if download_status:
                create_task(fileName, 0, '文件下载成功')
                input_file = os.path.join(BASE_DIR, DOWNLOAD_TMP, fileName)
                Thread(target=topaz_cmd, args=(input_file, scale)).start()
                return 'ok'
            else:
                create_task(fileName, 1, '文件下载失败')
                return 'fail'
def topaz_cmd(input_file, scale):
    scale = int(scale)
    task_code = -1
    file_name = os.path.basename(input_file)
    file_id = file_name
    if scale<=6:
        OUT_DIR = os.path.join(BASE_DIR, 'out')
        set_scale(scale)
        cmd = f'{TOPAZ_DIR}\\tpai.exe {input_file} --output {OUT_DIR}'
        logger.debug(f'cmd:{cmd}')
        task_code = exec_cmd(cmd)
        update_by_id(file_id, {'task_code': task_code})
    elif scale==8:
        logger.info('二次放大step1：4*2')
        OUT_DIR = os.path.join(BASE_DIR, 'out2')
        set_scale(4)
        cmd = f'{TOPAZ_DIR}\\tpai.exe {input_file} --output {OUT_DIR}'
        logger.debug(f'cmd:{cmd}')
        task_code = exec_cmd(cmd)
        if task_code == 0:
            logger.info('二次放大step2：4*2')
            input_file = os.path.join(BASE_DIR, 'out2',file_name)
            OUT_DIR = os.path.join(BASE_DIR, 'out')
            set_scale(2)
            cmd = f'{TOPAZ_DIR}\\tpai.exe {input_file} --output {OUT_DIR}'
            logger.debug(f'cmd:{cmd}')
            task_code = exec_cmd(cmd)
            if task_code != 0:
                update_by_id(file_id, {'status_code': 3, 'status_desc': '二次放大失败，失败步骤2'})
        else:
            update_by_id(file_id, {'status_code': 3, 'status_desc': '二次放大失败，失败步骤1'})

    elif scale==16:
        logger.info('二次放大step1：4*4')
        OUT_DIR = os.path.join(BASE_DIR, 'out2')
        set_scale(4)
        cmd = f'{TOPAZ_DIR}\\tpai.exe {input_file} --output {OUT_DIR}'
        logger.debug(f'cmd:{cmd}')
        task_code = exec_cmd(cmd)
        if task_code == 0:
            logger.info('二次放大step2：4*4')
            input_file = os.path.join(BASE_DIR, 'out2',file_name)
            OUT_DIR = os.path.join(BASE_DIR, 'out')
            set_scale(4)
            cmd = f'{TOPAZ_DIR}\\tpai.exe {input_file} --output {OUT_DIR}'
            logger.debug(f'cmd:{cmd}')
            task_code = exec_cmd(cmd)
            if task_code != 0:
                update_by_id(file_id, {'status_code': 3, 'status_desc': '二次放大失败，失败步骤2'})
        else:
            update_by_id(file_id, {'status_code': 3, 'status_desc': '二次放大失败，失败步骤1'})

    if task_code == 0:
        #完成后，上传七牛
        out_file = os.path.join(BASE_DIR, 'out', file_name)
        logger.debug(out_file)
        pan123_file_name = upload_file_pan123(out_file)
        if pan123_file_name == None:
            time.sleep(2)
            pan123_file_name = upload_file_pan123(out_file)
        #123上传后，等待一下，放至直链请求不到
        time.sleep(5)
        logger.info(f'pan123_file_name:{pan123_file_name}')
        ret, after_link = upload2qiniu(out_file, 'after')
        update_by_id(file_id, {'after_link': after_link,'pan123_file_name': pan123_file_name, 'status_code': 2,'status_desc':'放大成功'})
        logger.info(f'{file_name}处理完成，资源地址：{after_link}')
        wx_user_id = file_name.split('--')[1]
        if len(file_id.split('--'))>4:
            wx_user_id = file_name.split('--')[2]
        logger.info(f'wx_user_id:{wx_user_id}')
        send_wx_template(file_name,pan123_file_name)
    else:
        update_by_id(file_id, {'status_code': 3, 'status_desc': '放大失败'})


if __name__ == '__main__':
    app_name = 'topaz-win-api-server'
    logger.remove()
    logger.add(sys.stdout, level=log_level)  # WARNING/INFO/ERROR/DEBUG,控制台只会输出比该等级高的日志，但在文件日志中会全部写入
    log_name = "logs/%s-{time}.log" % app_name  # 配置文件路径，自动创建日志目录，{time}为内置变量，保证 日志文件的唯一性
    logger.add(log_name, encoding='utf-8', retention="10 days")

    name_app = os.path.basename(__file__)[0:-3]  # Get the name of the script
    uvicorn.run(app, host=host, port=int(port), reload=False)
